package com.hunktimes.wholesale.ui.pages

import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.google.android.material.tabs.TabLayoutMediator
import com.hunktimes.wholesale.R
import com.hunktimes.wholesale.base.BasePageFragment
import com.hunktimes.wholesale.databinding.TitleTabViewpagerBinding
import com.hunktimes.wholesale.util.Constants
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * Author: Delete
 * Date: 2020/7/27 19:22
 * Description:
 *
 */
class MyOrderFragment : BasePageFragment(R.layout.title_tab_viewpager) {
    lateinit var viewBinding: TitleTabViewpagerBinding
    override val titleRes: Int
        get() = R.string.title_order

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewBinding = TitleTabViewpagerBinding.bind(view)
    }

    override fun onStart() {
        super.onStart()
        initTabLayout()
    }

    override fun onResume() {
        super.onResume()
        selectSpecificTabDelay()
    }

    private fun selectSpecificTabDelay() {
        arguments?.getInt(Constants.key_selected_tab)?.let {
            if (it < 0 || it >= viewBinding.tabLayout.tabCount) return
            lifecycleScope.launch {
                delay(500)//不延迟的话 viewPager不联动
                viewBinding.tabLayout.selectTab(viewBinding.tabLayout.getTabAt(it))
            }
        }
    }

    val titles = arrayOf("全部", "待付款", "待發貨", "待收貨", "待評價")
    fun initTabLayout() {
        viewBinding.viewPager.adapter = OrderTabAdapter(this)

        TabLayoutMediator(viewBinding.tabLayout, viewBinding.viewPager) { tab, position ->
            tab.setCustomView(R.layout.tab_view_simple)
            tab.customView!!.findViewById<TextView>(R.id.tab_text).text = titles[position]
            tab.view.setBackgroundColor(
                ContextCompat.getColor(
                    requireContext(),
                    android.R.color.transparent
                )
            )
        }.attach()
    }

    inner class OrderTabAdapter(fragment: Fragment) : FragmentStateAdapter(fragment) {
        override fun getItemCount(): Int = titles.size

        override fun createFragment(position: Int): Fragment {
            val bundle = bundleOf(Constants.key_order_tab_type to position)
            return OrderListFragment.newInstance(bundle)
        }

    }
}